<template>
  <div style="width: 50%;background-color: #bfbfbf">
    <div style="font-size: 15px">
      个人中心
    </div>
    <el-form label-width="80px"
             style="padding: 20px 30px 0 0">

      <el-form-item prop="name" label="姓名">
        <el-input v-model="data.user.name" autocomplete="off" placeholder="请输入姓名"/>
      </el-form-item>
      <el-form-item prop="username" label="账号">
        <el-input v-model="data.user.username" autocomplete="off" placeholder="请输入账号"/>
      </el-form-item>
      <el-form-item prop="phone" label="手机号">
        <el-input v-model="data.user.phone" autocomplete="off" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="data.user.email" autocomplete="off" placeholder="请输入邮箱"/>
      </el-form-item>
      <el-form-item prop="avatar" label="头像">
        <el-upload action="http://localhost:8080/files/upload"
                   :on-success="handleFileSuccess"
                   :headers="{token :data.user.token}"
                   list-type="picture"
        >
          <el-button type="primary">上传头像</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <div style="text-align: center">
      <el-button @click="update" type="success" size="large" style="margin: 20px 50px;width: 80px">
        保存
      </el-button>
    </div>
  </div>
</template>
<script setup>
import {reactive, ref} from "vue";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

const formRef = ref()

const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || '{}'),
})
const handleFileSuccess = (res) => {
  data.user.avatar = res.data
  console.log(data.user)
}

const update = (res) => {
  let url = null
  if (data.user.role === 'ADMIN') {
    url = '/admin/update'
  } else if (data.user.role === 'USER') {
    url = '/user/update'
  } else {
    ElMessage.error('用户数据异常，请重新登录')
    localStorage.removeItem('code_user')
    router.push('/login')
  }
  request.put(url, data.user).then((res) => {
    console.log(res)
    if (res.code === 200) {
      ElMessage.success('信息修改成功')
      localStorage.setItem('code_user', JSON.stringify(data.user))
      // location.reload()
      emit('updateAccountName')
    }
  })
}
const emit=defineEmits(["updateAccountName"])


</script>
